const { verify } = require('../utils/jwt');
const message = require('../model/returnMessage');
const { jwtSecret } = require('../config/config.default');

module.exports = async (req, res, next) => {
  let token = req.headers['authorization'];
  token = token ? token.split('Bearer ')[1] : null;

  if (!token) {
    res.status(401).json(message({}, 'Invalid token.'));
  }

  verify(token, jwtSecret).then(
    (r) => {
      req.body.username = r.username;
      next();
    },
    (e) => {
      res.status(401).json(message({}, 'Invalid token.'));
    }
  );
};
